package com.web.wechat.global.filter;

import com.blue.http.config.ErrorConfig;
import com.blue.http.invoke.InvokerFilter;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.message.View;
import com.blue.http.util.HttpException;
import com.web.core.cache.ConfigCache;
import com.web.core.util.Const;
import com.web.wechat.global.model.User;
import com.web.wechat.global.util.HttpContext;

import javax.annotation.Resource;

/**
 * @author zhengjin
 * @since 1.0 2018年03月27日
 */
public class ContextFilter implements InvokerFilter
{
	@Resource
	private ConfigCache configCache;
	@Resource
	private HttpContext httpContext;

	private ErrorConfig errorConfig = ErrorConfig.getInstance();

	public ContextFilter()
	{
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
		User user = httpContext.getUser(request);
		if (user == null)
		{
			httpContext.setLastUrl(request, request.getUrl(), request.getQueryString());
			this.error(request, response);
			return false;
		}

		response.param().put("user", user);
		return true;
	}

	@Override
	public void afterHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
	}

	private void error(HttpRequest request, HttpResponse response)
	{
		String path = configCache.getValue(Const.WECHAT_PATH);
		String code = configCache.getValue(Const.WECHAT_CODE);
		String html = request.isWechat() ? "/app/oauth/code" : "/app/login";

		String ajax = request.getPost("_isAjax");
		if ("true".equals(ajax)) // 如果是ajax提交
		{
			response.setCode(ErrorConfig.SESSION);
			response.setMsg(errorConfig.get(ErrorConfig.SESSION));
		}
		else
		{
			String url = path + "/.." + request.getUrl();
			String queryString = request.getQueryString();
			httpContext.setLastUrl(request, url, queryString);
			View view = View.createBuilder().setLocation(path + html).build();
			response.setView(view);
		}

	}

}
